package com.self.war.view;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lexaden.grid.Grid;
import com.lexaden.grid.PagedTable;
import com.myself.entities.Post;
import com.self.war.presenter.UserPresenter;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
@Component
public class UserView extends CustomLayout implements View {
	public static final String VIEW_NAME = "user";

	@Autowired
	UserPresenter userPresenter;

	public UserView() {
		super("mylayout");
	}

	@Override
	public void enter(ViewChangeEvent event) {
		initLayout();
	}

	/**
	 * initialize layout of the user view
	 */
	private void initLayout() {
		initHeader();
		initMenu();
		initContent();
		initFooter();
		setSizeFull();
	}

	/**
	 * initialize the header
	 */
	private void initHeader() {
		// set up header
		Label header = new Label("Custom layout");
		header.addStyleName("header");
		addComponent(header, "header");
	}

	/**
	 * initialize the menu
	 */
	private void initMenu() {
		// set up menu
		Label menu = new Label("menu");
		addComponent(menu, "menu");
	}

	/**
	 * initialize the content
	 */
	private void initContent() {
		List<Post> posts = userPresenter.getPosts();
		final VerticalLayout content = new VerticalLayout();

		final PagedTable table = new PagedTable();

		table.setContainerDataSource(new BeanItemContainer<Post>(Post.class,
				posts));
		table.setWidth(100, Unit.PERCENTAGE);
		int tableSize = table.size();
		if (tableSize > 20) {
			table.setHeight(400, Unit.PERCENTAGE);
		}
		table.setPageLength(tableSize);
		table.setColumnCollapsingAllowed(true);
		table.setColumnReorderingAllowed(true);

		table.setVisibleColumns(new Object[] { "title", "postDate" });

		table.setColumnHeaders(new String[] { "Title", "Post date" });
		table.setPageLength(5);
		table.setSelectable(true);
		final Grid grid = new Grid(table);
		grid.setSizeFull();
		content.addComponent(grid);
		addComponent(content, "content");
	}

	/**
	 * initialize the footer
	 */
	private void initFooter() {
		// set up footer
		Label footer = new Label("Created by Vaadin, 2013");
		addComponent(footer, "footer");
	}

	public UserPresenter getUserPresenter() {
		return userPresenter;
	}

	public void setUserPresenter(UserPresenter userPresenter) {
		this.userPresenter = userPresenter;
	}

}
